import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:tot_android_flutter/utils/JsonUtil.dart';

import '../../log_util.dart';

class DioLogInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    StringBuffer buffer = StringBuffer();
    buffer.write('⌈‾‾ Request ヾ(•ω•`)o \n');
    buffer.write('| \n');
    buffer.write('| - Uri：   ${options.uri}\n');
    buffer.write('| - Method：${options.method}\n');
    buffer.write('| - Header：${options.headers.toString()}\n');
    final data = options.data;
    if (data != null) {
      if (data is Map) {
        buffer.write('| - Body：  ${options.data.toString()}\n');
      } else if (data is FormData) {
        final formDataMap = {}
          ..addEntries(data.fields)
          ..addEntries(data.files);
        buffer.write("| - Body：  ${formDataMap.toString()}\n");
      } else {
        buffer.write("| - Body：  ${data.toString()}\n");
      }
    }
    buffer.write(
        '⌊_____________________________________________________________________');
    printDebugLog(buffer);
    return handler.next(options);
  }

  @override
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    //返回自定义的Base
    // final baseResponse = BaseResponse(code: response.statusCode, msg: response.statusMessage, data: response.data);
    // response.data = baseResponse;

    StringBuffer buffer = StringBuffer();
    buffer.write('⌈‾‾ Response O(∩_∩)O \n');
    buffer.write('| \n');
    buffer.write('| - Code：   ${response.statusCode}\n');
    buffer.write('| - CodeMsg：${response.statusMessage}\n');
    buffer.write('| - Header：\n');
    response.headers.forEach((key, value) {
      buffer.write('|    $key  $value\n');
    });
    final data = response.data;
    if (data != null) {
      if (data is Map) {
        buffer.write('| - Data：  ${response.toString()}\n');
        String dataJson = jsonEncode(JsonUtils.toJson(response.toString()));
        buffer.write('| - Json：  $dataJson\n');
      } else if (data is FormData) {
        final formDataMap = {}
          ..addEntries(data.fields)
          ..addEntries(data.files);
        buffer.write("| - Data：  ${formDataMap}\n");
      } else {
        buffer.write("| - Data：  ${response.toString()}\n");
      }
    }
    buffer.write(
        '⌊_____________________________________________________________________');
    printDebugLog(buffer);
    return handler.next(response);
  }

  void printDebugLog(StringBuffer buffer) {
    WanLog.i(buffer.toString());
  }
}
